package cn.yusei.teamTribe.service.post;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.constant.PostTagType;
import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.dao.post.PostDAO;
import cn.yusei.teamTribe.dao.post.PostTagDAO;
import cn.yusei.teamTribe.dao.post.po.PostTagPO;
import cn.yusei.teamTribe.service.PermissionService;

@Service
public class PostTagService {

	@Autowired
	private PostTagDAO postTagDAO;
	@Autowired
	private PostDAO postDAO;
	@Autowired
	private PermissionService permissionService;
	
	public int add(int userId, int postId, int tagId)
	{
		boolean needInformPermission = false;
		//把帖子改为通知帖，需要设置通知帖的权利
		if(tagId == PostTagType.INFORM_POST)
		{
			needInformPermission = true;
			Integer targetId = postDAO.selectTargetIdById(postId);
			if(targetId == null)
				return ResponseCode.POST_NOT_EXISTS;
			//不能把评论设置为通知帖
			if(targetId != 0)
				return ResponseCode.PARAM_ILLEGAL;
		}
		if(!permissionService.havePostPermission(userId, postId, needInformPermission))
			return ResponseCode.PERMISSION_FORBIDDEN;
		PostTagPO postTagPO = new PostTagPO();
		postTagPO.setPostId(postId);
		postTagPO.setTagId(tagId);
		if(postTagDAO.exists(postTagPO))
			return ResponseCode.REQUEST_SUCCESSED;
		postTagDAO.insert(postTagPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
	public int delete(int userId, int postId, int tagId)
	{
		//不能把通知帖变为普通帖
		if(tagId == PostTagType.INFORM_POST)
			return ResponseCode.PARAM_ILLEGAL;
		PostTagPO postTagPO = new PostTagPO();
		postTagPO.setPostId(postId);
		postTagPO.setTagId(PostTagType.INFORM_POST);
		if(!permissionService.havePostPermission(userId, postId, false))
			return ResponseCode.PERMISSION_FORBIDDEN;
		postTagPO.setTagId(tagId);
		if(!postTagDAO.exists(postTagPO))
			return ResponseCode.REQUEST_SUCCESSED;
		postTagDAO.delete(postTagPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
	public int[] get(int postId)
	{
		int[] tags = postTagDAO.selectTagById(postId);
		return tags;
	}
}
